import { createRouter, createWebHistory,createWebHashHistory } from 'vue-router'
import login from '@/views/login/index.vue'
import shouye from '@/views/shouye/index.vue'
import jiazi from '@/views/layout/index.vue'
import department from '@/views/system/department_manager/index.vue'
import my_menu from '@/views/system/menu_manager/index.vue'
import position from '@/views/system/position_manager/index.vue'
import role from '@/views/system/role_manager/index.vue'
import service from '@/views/system/service_manager/index.vue'
import user_manager from '@/views/system/user_manager/index.vue'
import {auth} from '@/apis/user'
import { UseInfo_Store } from '@/stores/index'
import { login_auth_Store } from '@/stores/index'


const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: login,
    },
    {
      path: '/',
      name: 'jiazi',
      component: jiazi,
      redirect: "/jiazi/shouye",
      children: [
        {
          path: '/jiazi/shouye', name:'shouye', component: shouye
        },
                {
          path: '/jiazi/department', name:'department', component: department
        },
                {
          path: '/jiazi/menu', name:'my_menu', component: my_menu
        },
                {
          path: '/jiazi/position', name:'position', component: position
        },
                {
          path: '/jiazi/role', name:'role', component: role
        },
                {
          path: '/jiazi/service', name:'service', component: service
        },
                {
          path: '/jiazi/user_manager', name:'user_manager', component: user_manager
        },
      ]
    },
  ],
})

router.beforeEach(async (to) => {
  console.log('路由守卫触发:', to.path)
  const userStore = UseInfo_Store()
  const authstore = login_auth_Store()
  if(!userStore.token && to.path !== '/login'){
    return '/login'
  }
if (userStore.token && authstore.caidan.length == 0  && to.path !== '/login') {
    try {
      console.log('当前Token状态:', userStore.token)
      const res = await auth() // 请求权限数据
      authstore.set_caidan(res.nav)
      console.log('当前菜单状态:', authstore.caidan)
      console.log('✅ 获取到权限数据:', res)

      // // 假设后端返回 { nav: [...], authoritys: [...] }
      // if (res && Array.isArray(res.nav)) {
      //   userStore.caidan = res.nav           // 存菜单
      //   authStore.buttons = res.authoritys || [] // 存按钮权限
      // } else {
      //   console.warn('⚠️ 权限接口返回数据格式异常:', res)
      //   throw new Error('权限数据格式错误')
      // }

    } catch (error) {
      console.error('❌ 请求权限失败:', error)
      // 可选：清空 token，防止死循环
      userStore.token = '' // 或 userStore.logout()
      return '/login'      // 跳转登录页
    }}

})

export default router
